package com.t.bricks.bussiness.db.dao.rechargecard.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.t.bricks.bussiness.db.dao.rechargecard.RechargeCardDao;
import com.t.bricks.bussiness.db.entity.rechargecard.RechargeCard;
import com.t.bricks.bussiness.db.entity.rechargecard.base.CustomerAccountBase;
import com.t.bricks.bussiness.db.entity.rechargecard.base.RechargeBase;
import com.t.bricks.bussiness.db.entity.rechargecard.base.RechargeCardBase;
import com.t.bricks.bussiness.db.mapper.rechargecard.RechargeCardMapper;
import com.t.bricks.bussiness.model.rechargecard.ConditionRechargeCard;
import com.t.bricks.model.Log;
import com.t.bricks.model.MsgEmity;
import com.t.bricks.model.OrderInfoList;
import com.t.bricks.model.Page;
import com.t.bricks.utils.function.data.IntegerUtil;

@Repository
public class RechargeCardDaoImpl implements RechargeCardDao {
	
	@Autowired
	private RechargeCardMapper rechargeCardMapper;

	@Value("${app.findPage.dLikeDate:配置文件中的当前库全文检索时间范围dLikeDate未设置}")
	private String sLikeDate;

	/**
	 * 批量添加
	 * @param list
	 * @return MsgEmity
	 */
	@Override
	public MsgEmity adds(List<RechargeCard> list) {
		List<RechargeCard> temp = new ArrayList<>(50);

		while(list.size() > 0) {
			for (int i = 0; i < (list.size() > 50 ? 50 : list.size()); i++) {
				temp.add(list.get(i));
			}
			
			try {
				int i = rechargeCardMapper.adds(temp);
				if (i < 1) {
					Log.error("批量新增未能得到预期影响值(预期", temp.size(), "):", i);
					return new MsgEmity(false, "新增数据失败！", 7001);
				}
				
				if (list.size() <= 0) {
					break;
				}
				
				Thread.sleep(1000);
			} catch (Exception e) {
				Log.error("批量新增时发生异常:", e.getMessage());
				return new MsgEmity(false, "批量新增失败！", 7002);
			}

			for (int i = 0; i < temp.size(); i++) {
				list.remove(temp.get(i));
			}
		}
		
		return new MsgEmity(true, "批量新增成功！", 7999);
	}

	/**
	 * 删除
	 * 注:只能删除未被领取的数据
	 * @param uId 记录编号
	 * @param iVersion 数据版本号
	 * @return MsgEmity
	 */
	@Override
	public MsgEmity del(String uId, Integer iVersion) {
		try {
			int i = rechargeCardMapper.del(uId, iVersion);
			if (i < 1) {
				List<String> fieldNames = Arrays.asList("iVersion", "sCustomerId");
				Map<String, Object> map = rechargeCardMapper.getValueByFieldName(uId, fieldNames);//如果删除的影响数小于1,则检查数据是否存在
				if (null == map) {
					return new MsgEmity(true, "成功，数据已经删除！", 7999);//删除影响数失败,但数据也不存在则视为成功
				}
				
				if (!iVersion.equals(map.get("iVersion"))) {
					return new MsgEmity(false, "删除数据失败，系统中的数据可能已经被更新！", 7001);
				}
				
				if (null != map.get("sCustomerId")) {
					return new MsgEmity(false, "删除数据失败，被领取的充值卡不能删除！", 7004);
				}

				Log.error("删除未能得到预期影响值(预期1):", i);
				return new MsgEmity(false, "删除数据失败！", 7002);
			}
		} catch (Exception e) {
			Log.error("删除时发生异常:", e.getMessage());
			return new MsgEmity(false, "删除失败！", 7003);
		}
		
		return new MsgEmity(true, "删除成功！", 7999);
	}
	
	/**
	 * 根据Id查询数据
	 * @param uId
	 * @return MsgEmity
	 */
	@Override
	public MsgEmity findById(String uId) {
		RechargeCard rechargeCard = null;
		try {
			rechargeCard = rechargeCardMapper.findById(uId);
			if (null == rechargeCard) {
				return new MsgEmity(false, "数据不存在！", 7001);
			}
		} catch (Exception e) {
			Log.error("查询发生异常:", e.getMessage());
			return new MsgEmity(false, "查询失败！", 7002);
		}
		
		return new MsgEmity(true, "查询成功！", rechargeCard);
	}
	
	/**
	 * 根据号码查询数据
	 * @param sNo
	 * @return MsgEmity
	 */
	@Override
	public MsgEmity findByNo(String sNo) {
		RechargeCard rechargeCard = null;
		try {
			rechargeCard = rechargeCardMapper.findByNo(sNo);
			if (null == rechargeCard) {
				return new MsgEmity(false, "数据不存在！", 7001);
			}
		} catch (Exception e) {
			Log.error("查询发生异常:", e.getMessage());
			return new MsgEmity(false, "查询失败！", 7002);
		}
		
		return new MsgEmity(true, "查询成功！", rechargeCard);
	}

	/**
	 * 根据字段名取指定记录编号的数据库表中对应字段的值
	 * @param uId
	 * @param fieldNames 待取数据的字段名称集合
	 * @return MsgEmity 返回内容data中存放的是Map
	 */
	@Override
	public MsgEmity getValueByFieldName(String uId, List<String> fieldNames) {
		//--检查实体类中是否有该字段,没有就不加入查询字段--//
		Class<?> clazz = RechargeCardBase.class;
		List<String> dbNames = new ArrayList<String>();
		for (String field : fieldNames) {
			try {
				if (clazz.getDeclaredField(field) != null) {
					dbNames.add(field);
				}
			} catch (Exception e) {
			}
		}
		
		if (dbNames.size() < 1) {
			return new MsgEmity(false, "没有对应的数据可查询！", 7001);
		}
		
		Map<String, Object> result = null;
		try {
			result = rechargeCardMapper.getValueByFieldName(uId, dbNames);
			if (null == result) {
				return new MsgEmity(false, "数据不存在！", 7002);
			}
		} catch (Exception e) {
			Log.error("查询发生异常:", e.getMessage());
			return new MsgEmity(false, "查询失败！", 7003);
		}
		
		//--补充字段--//
		for (String string : fieldNames) {
			if (!result.containsKey(string)) {
				result.put(string, null);
			}
		}
		
		return new MsgEmity(true, "查询成功！", result);
	}

	/**
	 * 根据关键值取对象集合
	 * @param rechargeCardData 存放查询条件的RechargeCard对象
	 * @return MsgEmity
	 */
	@Override
	public MsgEmity findByKey(RechargeCard rechargeCardData) {
		List<RechargeCard> list = null;
		try {
			list = rechargeCardMapper.findByKey(rechargeCardData);
			if (null == list) {
				return new MsgEmity(false, "数据不存在！", 7001);
			}
			if (list.size() < 1) {
				return new MsgEmity(true, "查询成功，但没有数据！", list);
			}
		} catch (Exception e) {
			Log.error("查询发生异常:", e.getMessage());
			return new MsgEmity(false, "查询失败！", 7002);
		}
		
		return new MsgEmity(true, "查询成功！", list);
	}

	/**
	 * 根据关键值查数量
	 * @param rechargeCardData 存放查询条件的RechargeCard对象
	 * @return MsgEmity
	 */
	@Override
	public MsgEmity findCountByKey(RechargeCard rechargeCardData) {
		int iCount = 0;
		try {
			iCount = rechargeCardMapper.findCountByKey(rechargeCardData);
		} catch (Exception e) {
			Log.error("查询发生异常:", e.getMessage());
			return new MsgEmity(false, "查询失败！", 7001);
		}
		
		return new MsgEmity(true, "查询成功！", iCount);
	}

	/**
	 * 查询分页信息
	 * @param page 分页信息对象
	 * @param orders 排序数据集合
	 * @param sLikeStr 全文检索
	 * @param condition 查询条件对象
	 * @return MsgEmity
	 */
	@Override
	public MsgEmity findByPage(Page page, OrderInfoList orders, String sLikeStr,
			ConditionRechargeCard condition) {
		if ("配置文件中的当前库全文检索时间范围dLikeDate未设置".equals(sLikeDate)) {
			sLikeDate = "3";
		}
		
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(new Date());
		calendar.add(Calendar.DATE, - IntegerUtil.strToInt(sLikeDate, 3));//日期加m天
		Date dLikeDateSt = calendar.getTime();
		Date dLikeDateEd = new Date();
		
		int iCount = 0;
		try {
			iCount = rechargeCardMapper.findByPageCount(sLikeStr, dLikeDateSt, dLikeDateEd, condition);
		} catch (Exception e) {
			Log.error("查询数量发生异常", e.getMessage());
			return new MsgEmity(false, "查询数量失败！", 7001);
		}
		
		if (iCount < 1) {
			return new MsgEmity(true, "没有相关数据！", page);
		}

		page.setCountRow(iCount);

		List<RechargeCard> list = null;
		try {
			list = rechargeCardMapper.findByPage(page,
					(null == orders) ? null : orders.getOrderInfoList(),
					sLikeStr, dLikeDateSt, dLikeDateEd, condition);
			if (null == list) {
				Log.error("查询数据发生异常,执行的返回值为:null,预期值不应为null");
				return new MsgEmity(false, "查询操作失败！", 7002);
			}
		} catch (Exception e) {
			Log.error("查询分页数据发生异常:", e.getMessage());
			return new MsgEmity(false, "查询请求失败，请查看异常日志！", 7003);
		}

		page.setRecordList(list);
		
		if (null != sLikeStr) {
			return MsgEmity.success(page, "查询成功！", "由于使用了全文检索,因此数据查询限制为近", sLikeDate, "天创建的数据");
		}
		
		return new MsgEmity(true, "查询成功！", page);
	}

	/**
	 * 根据记录编号查询符合分页数据的某条记录
	 * @param uId 记录编号
	 * @return MsgEmity
	 */
	@Override
	public MsgEmity findByPageRow(String uId) {
		RechargeCard rechargeCard = null;
		try {
			rechargeCard = rechargeCardMapper.findByPageRow(uId);
			if (null == rechargeCard) {
				return new MsgEmity(false, "数据不存在！", 7001);
			}
		} catch (Exception e) {
			Log.error("查询发生异常:", e.getMessage());
			return new MsgEmity(false, "查询失败！", 7002);
		}
		
		return new MsgEmity(true, "查询成功！", rechargeCard);
	}
	
	/**
	 * 查询搜索用的数据
	 * 警告:本方法只允许内部使用,不能开放到外部接口
	 * @param whereStr 查询条件字符串
	 * @param orders 排序数据集合
	 * @return MsgEmity
	 */
	@Override
	public MsgEmity findBySearch(String whereStr, OrderInfoList orders) {
		if (null == whereStr || "".equals(whereStr.trim())) {
			return new MsgEmity(false, "查询条件不允许为空！", 7001);
		}

		List<RechargeCard> list = null;
		try {
			list = rechargeCardMapper.findBySearch(whereStr.trim(),
					(null == orders) ? null : orders.getOrderInfoList());
			if (null == list) {
				Log.error("查询数据发生异常,执行的返回值为:null,预期值不应为null");
				return new MsgEmity(false, "查询操作失败！", 7002);
			}
		} catch (Exception e) {
			Log.error("查询分页数据发生异常:", e.getMessage());
			return new MsgEmity(false, "查询请求失败，请查看异常日志！", 7003);
		}
		
		return new MsgEmity(true, "查询成功！", list);
	}

	/**
	 * 查询导出到文件的数据
	 * @param orders 排序数据集合
	 * @param sLikeStr 全文检索
	 * @param condition 查询条件对象
	 * @return MsgEmity
	 */
	@Override
	public MsgEmity findByExport(OrderInfoList orders, String sLikeStr, ConditionRechargeCard condition) {
		if ("配置文件中的当前库全文检索时间范围dLikeDate未设置".equals(sLikeDate)) {
			sLikeDate = "3";
		}
		
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(new Date());
		calendar.add(Calendar.DATE, - IntegerUtil.strToInt(sLikeDate, 3));//日期加m分
		Date dLikeDateSt = calendar.getTime();
		Date dLikeDateEd = new Date();
		
		List<RechargeCard> list = null;
		try {
			list = rechargeCardMapper.findByExport(
					(null == orders) ? null : orders.getOrderInfoList(),
					sLikeStr, dLikeDateSt, dLikeDateEd, condition);
			if (null == list) {
				Log.error("查询数据发生异常,执行的返回值为:null,预期值不应为null");
				return new MsgEmity(false, "查询操作失败！", 7001);
			}
		} catch (Exception e) {
			Log.error("查询导出文件用的数据发生异常:", e.getMessage());
			return new MsgEmity(false, "查询请求失败，请查看异常日志！", 7002);
		}
		
		return new MsgEmity(true, "查询成功！", list);
	}

	//----------------------------- 自动生成代码结束 ---------------------------//

	/**
	 * 按编号占用
	 * @param rechargeCard
	 * @return
	 */
	@Override
	public MsgEmity employById(RechargeCard rechargeCard) {
		try {
			int i = rechargeCardMapper.employById(rechargeCard);
			if (i < 1) {
				Log.error("按编号占用操作执行成功但未能得到预期影响值(预期1):", i);
				return new MsgEmity(false, "占用操作执行成功但未能得到预期影响值(预期1)", 7001);
			}
			
			return new MsgEmity(true, "占用操作执行成功！", 7999);
		} catch (Exception e) {
			Log.error("按编号占用操作发生异常:", e.getMessage());
			return new MsgEmity(false, "按编号占用操作失败！", 7003);
		}
	}

//	/**
//	 * 充值卡充值
//	 * @param rechargeCard
//	 * @param rechargeBase
//	 * @param customerAccountBase
//	 * @return MsgEmity
//	 */
//	@Override
//	@Transactional
//	public MsgEmity recharge(RechargeCard rechargeCard, RechargeBase rechargeBase,
//			CustomerAccountBase customerAccountBase) {
//		try {
//			int i = rechargeCardMapper.useById(rechargeCard);
//			if (i < 1) {
//				Log.error("按编号使用操作执行成功但未能得到预期影响值(预期1):", i);
//				return new MsgEmity(false, "按编号使用执行成功但未能得到预期影响值(预期1)", 7001);
//			}
//			
//			i = rechargeCardMapper.addRecharge(rechargeBase);
//			if (i < 1) {
//				Log.error("按编号占用操作执行成功但未能得到预期影响值(预期1):", i);
//				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚事务
//				return new MsgEmity(false, "占用操作执行成功但未能得到预期影响值(预期1)", 7002);
//			}
//			
//			i = rechargeCardMapper.changeCustomerAccount(customerAccountBase);
//			if (i < 1) {
//				Log.error("更新顾客账户中的余额操作执行成功但未能得到预期影响值(预期1):", i);
//				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚事务
//				return new MsgEmity(false, "更新顾客账户中的余额执行成功但未能得到预期影响值(预期1)", 7003);
//			}
//			
//			return new MsgEmity(true, "充值卡充值操作执行成功！", 7999);
//		} catch (Exception e) {
//			Log.error("按编号占用操作发生异常:", e.getMessage());
//			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚事务
//			return new MsgEmity(false, "按编号占用操作失败！", 7004);
//		}
//	}
	
	/**
	 * 将过期数据更新状态
	 * @param rechargeCard
	 * @return
	 */
	@Override
	public MsgEmity expire(RechargeCard rechargeCard) {
		try {
			int i = rechargeCardMapper.expire(rechargeCard);
			return MsgEmity.success(i, "检查过期数据执行成功,影响数:");
		} catch (Exception e) {
			Log.error("检查过期数据时发生异常:", e.getMessage());
			return new MsgEmity(false, "检查过期数据失败！", 7003);
		}
	}
	
	/**
	 * 取过期数据
	 * @return
	 */
	@Override
	public MsgEmity expireData() {
		try {
			List<RechargeCard> list = rechargeCardMapper.expireData();
			if (null == list) {
				Log.error("取过期数据发生异常,执行的返回值为:null,预期值不应为null");
				return new MsgEmity(false, "取过期数据失败！", 7001);
			}
			
			return new MsgEmity(true, "查询成功！", list);
		} catch (Exception e) {
			Log.error("取过期数据发生异常:", e.getMessage());
			return new MsgEmity(false, "查询请求失败，请查看异常日志！", 7002);
		}
	}
	
	/**
	 * 查询顾客所持充值卡
	 * @param iState
	 * @param sCustomerId
	 * @return MsgEmity List<RechargeCard>
	 */
	@Override
	public MsgEmity findByCustomer(Integer iState, String sCustomerId) {
		try {
			List<RechargeCard> list = rechargeCardMapper.findByCustomer(iState, sCustomerId);
			if (null == list) {
				Log.error("查询顾客所持充值卡发生异常,执行的返回值为:null,预期值不应为null");
				return new MsgEmity(false, "查询操作失败！", 7001);
			}
			
			return new MsgEmity(true, "查询成功！", list);
		} catch (Exception e) {
			Log.error("查询顾客所持充值卡发生异常:", e.getMessage());
			return new MsgEmity(false, "查询请求失败，请查看异常日志！", 7002);
		}
	}
	
	/**
	 * 查询顾客账户
	 * @param sId
	 * @return
	 */
	@Override
	public MsgEmity findCustomer(String sId) {
		CustomerAccountBase customerAccountBase = null;
		try {
			customerAccountBase = rechargeCardMapper.findCustomer(sId);
		} catch (Exception e) {
			Log.error("查询发生异常:", e.getMessage());
			return new MsgEmity(false, "查询失败！", 7002);
		}
		
		return new MsgEmity(true, "查询成功！", customerAccountBase);
	}
	
	/**
	 * 同步更新顾客账户中的余额
	 * @param rechargeCard
	 * @param rechargeBase
	 * @param customerAccountBase
	 * @return
	 */
	@Override
	@Transactional
	public MsgEmity changeCustomerAccount(RechargeCard rechargeCard, RechargeBase rechargeBase,
			CustomerAccountBase customerAccountBase) {
		if (rechargeCard.getiState() != 4) {
			return new MsgEmity(false, "此方法只能用于修改状态为4的订单！", 7001);//删除影响数失败,但数据也不存在则视为成功
		}
		
		try {
			int i = rechargeCardMapper.changeState(rechargeCard);
			if (i < 1) {
				return new MsgEmity(false, "更新状态数据失败！", 7006);
			}
			
			i = rechargeCardMapper.addRecharge(rechargeBase);
			if (i < 1) {
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚事务
				return new MsgEmity(false, "更新状态数据失败,未能添加积分日志信息！", 7007);
			}
			
			i = rechargeCardMapper.changeCustomerAccount(customerAccountBase);
			if (i < 1) {
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚事务
				return new MsgEmity(false, "更新状态数据失败,未能更新账户信息！", 7008);
			}
		} catch (Exception e) {
			Log.error("更新状态时发生异常:", e.getMessage());
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚事务
			return new MsgEmity(false, "更新状态失败！", 7009);
		}
		
		return new MsgEmity(true, "更新状态成功！", 7999);
	}
	
	/**
	 * 错误值累加
	 * @param uId
	 * @param tableName
	 * @return
	 */
	@Override
	public MsgEmity addErrorCount(String uId, String tableName) {
		try {
			int i = rechargeCardMapper.addErrorCount(uId, tableName);
			if (i < 1) {
				return new MsgEmity(false, "错误值累加失败！", 7001);
			}
		} catch (Exception e) {
			Log.error("错误值累加发生异常:", e.getMessage());
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//手动回滚事务
			return new MsgEmity(false, "错误值累加失败！", 7002);
		}
		
		return new MsgEmity(true, "错误值累加成功！", 7999);
	}

}
